# -*- coding: utf-8 -*-
"""
Created on Wed Dec 27 15:25:56 2017

@author: za-xuzhaoye
"""

from RSRS_signal_construction import signal_construction, RSRS,CalculateResult
import pandas as pd
#import numpy as np 
import tushare as ts
from arr import Ashare,AH,ETF
from pandas import Series


basicinfo=ts.get_stock_basics()
idlist=Series(basicinfo.index)

#idlist= Ashare
Results=pd.DataFrame()
#Recommandation=pd.DataFrame()


def ResultCalculate(idlist,Results):
    for i in range(1,len(idlist)):
        try:
        
            SecurityId=idlist[i]
            mktdata=ts.get_k_data(SecurityId,start='2017-01-01',end='2018-01-15').sort_index()
            popen = mktdata['open'].values
            pclose = mktdata['close'].values
            phigh = mktdata['high'].values
            plow = mktdata['low'].values
            
            b,up,down=RSRS(SecurityId,mktdata,popen,pclose,phigh,plow)
            tdbook, sgn_hd, holdprice,longsgnrate,shortsgnrate=signal_construction(mktdata,
                                                                        SecurityId,b,up,down,pclose,popen)
            TradeRecord,Result=CalculateResult(mktdata,SecurityId,tdbook,sgn_hd,holdprice,pclose,
                                               capital=1000000,unit=100,rate=0.0025, year=270, rf=0.0035)
        
            print Result
         
            Results=pd.concat([Results,Result])
            
        except:
            print "Error " + SecurityId

    #        tmp1=Results['AnnualReturn']>=Results['LongTermHoldingReturn']
    #        win=np.where(tmp1==True,1,0)
    #        win1=sum(win)2
    #        winnerRate= win1/float(len(Results))
    #        
    #        tmp2=Recommand['ProfitRate']>0
    #        Gain=np.where(tmp2==True,1,0)
    #        Gain1=sum(Gain)
    #        GainRate=Gain1/float(len(Recommand))
    return Results
Results=ResultCalculate(idlist,Results)


Recommand=Results.loc[(Results['Position']>0)&(Results['Profit']>0)]
Shortsgn=Results.loc[Results['Position']<0]
#%%
Recommandtop10Profit=Recommand.sort_values(['Profit'],ascending=False).head(10)            
Recommandtop10longsgn=Recommand.sort_values(['Longsgnrate','Profit'],ascending=False).head(30)

    
Results.to_csv('D:\FOF_strategy\RSRS\Report\Result20180115.csv',index=False)
Shortsgn.to_csv('D:\FOF_strategy\RSRS\Report\Shortsgn20180115.csv',index=False)
Recommandtop10Profit.to_csv('D:\FOF_strategy\RSRS\Report\Recommandtop10Profit20180115.csv',index=False)
Recommandtop10longsgn.to_csv('D:\FOF_strategy\RSRS\Report\Recommandtop10longsgn20180115.csv',index=False)

